<?
class form
{
	public $include;
	public $table;
	public $index;
	public $indexname; 
	public $title;
	public $submit;
	public $action;
	public $variables;
	public $query;
	public $properties;
	public $BackURL;
	public $Addnew;
	public $update;
	public $content;
	public $handle;
	public $notify;
	public $operation;
	
   /**
    * Creates an HTML form from database and given stuff
    *
    * @return HTML form
    */
   function CreateForm(){

   	 if(is_array($this->include) || $this->content){
 		
   	 	if(!$this->update)
   	 		$this->update = 1;
   	 	
   	 	//if there is an index, work on fillin the values.
   	 	if ($this->index && $this->update == 1){
   	 		while (list($x,$y) = each($this->include)){
				 if(!is_array($y))
				 	$q[$x] = $y; 
				 else 
				 	$q[$x] = $y['id'];
   	 		}
   	 		$values = join(",",$q);
   	 		$res = dbQuery("select ".$values." from ".$this->table." where ".$this->indexname."='".$this->index."'") or die(dbError());
   	 		$row = dbFetchArray($res);
   	 	}
   	 	
   	 	//create the html
   	 	$output .= "<form action='".$this->action."' method='post' enctype='multipart/form-data' onSubmit='".$this->onsubmit."' name='".$this->name."'>";
   	 	
   	 	
   	 	//if add new link is enabled, put it 
   	 	if($this->Addnew){
   	 		if(is_array($this->Addnew['param']))
   	 		   $link = $this->CreateWebQuery($this->Addnew['param'],$this->Addnew['url']);
   	 		else 
   	 			$link =  $this->Addnew['url'];
   	 			
   	 		//create the link	
   	 		$output .= "<a href='".$link;
   	 		$output .= "'>".$this->Addnew['text']."</a>";
   	 	}
   	 	//start with the form
   	 	$output .= "<table width=100% class='".$this->properties['style']."'>";
                $output .= "<thead>";
   	 	if($this->title)
   	 	$output .= "<tr><th colspan=2>".$this->title."</th></tr>";
                $output .= "</thead>";
   	 	if(!$this->content){
   	 		//loop through to create the form
   	 		reset($this->include);
   	 		while(list($caption,$name) = each($this->include)){
   	 			if(!is_array($name)){
   	 				$output .= "<tr>";
   	 				$output .= "<td>".$caption."</td>";
   	 				$output .= "<td><input type='text' name='".$name."' value='".$row[$name]."'></td>";
   	 				$output .= "</tr>";
   	 			}else{
                                        $type   = $name['type'];
   	 				$query 	= $name['query'];
   	 				$id		= $name['id'];
   	 				$v		= $name['v'];
                                        $all            = $name['all'];
					if($type != "hidden"){
                                        $output .= "<tr>";
   	 				$output .= "<td>".$caption."</td>";
   	 				$output .= "<td>";
					}
                                        // Everything is filled up fine, let's parse
   	 				if($query && $id && $v){
                                                if($type == "select"){
   	 					$res = dbQuery($query) or die(dbError());
   	 					$output .= "<select name='".$id."'>";
                                                        if($all)
                                                                $output .= '<option value="" selected>Select</option>';
                        
                                                        // Select the apprpriate value if editing
                                                        while($r = dbFetchArray($res)){
                                                        	$output .= "<option value='".$r[$id]."'";
                                                        	if($r[$id] == $row[$name['id']])
                                                        		$output .= " selected";
                                                        	if(!strpos($v,"##")){
                                                        		$output .= ">".$r[$v]."</option>";
                                                        	}else{ 
                                                        		$val = $this->ReplaceKeys($r,$v);
                                                        		$output .= ">".$val."</option>";
                                                        	}
                                                        }
                                                        $output .= "</select>";
                                                       
                                                }
                                                //custom select, just pass a query
                                                 if($type == "cselect"){
   	 					
   	 					$output .= "<select name='".$id."'>";
                                                        if($all)
                                                                $output .= '<option value="" selected>Select</option>';
                        
                                                        // Select the apprpriate value if editing
                                                        while(list($key,$value) = each($query)){
                                                        	$output .= "<option value='".$key."'";
								if($key == $row[$name['id']])
                                                        		$output .= " selected";
                                                        	$output .= ">".$value."</option>";
                                                        }
                                                        $output .= "</select>";
                                                       
                                                }
                                                //what if it is a file
                                                if($type == 'file'){
                                                    $output .="<input name='".$id."' type='file' value='".$v."'>";    
                                                }
                                                
                                                //add date /time input
                                                if($type == 'calendar'){
                                                   list($key,$value) = each($query);
                                                    $output .="<script type=\"text/javascript\">";
                                                    $output .="$(function() {\n";
                                                    $output .="$('#".$id."').datetimepicker({ \n";
                                                    $output .= $key.": '".$value."'";
                                                    $output .="});\n});";
                                                    $output .="</script>\n";
                                                    $output .="<input type='text' id='".$id."' name='".$id."' value='".$row[$name['id']]."'>";   
                                                }
						if($type =='checkbox'){
						   $output .="<input type='checkbox' name='".$id."' value='1'";
						   if($row[$id] == 1)
							$output .=" checked ";
						   $output .=">";
						}
                                                if($type=="password")
						{
							$output .="<input type='password' id='".$id."' name='".$id."'/>";   	
						}
                                                if($type =='monthselect'){
                                                        $output .="<select name='".$id."'>";
                                                        for ($p=1; $p<=12; $p++){
                                                        //create months
                                                                $output .="<option value='".$p."'";
                                                                if($p == date("m"))
                                                                        $output .="selected ";
                                                                $output .=">".$p."</option>";
                                                        }
                                                	$ouptput .="</select>";
                                                }
                                                
                                                if($type == 'yearselect'){
                                                        $output .="<select name='".$id."'>";
                                                        for ($i=$this->properties['startyear'];$i<=$this->properties['endyear'];$i++){
                                                        //create months
                                                        $output .="<option value='".$i."'";
                                                        if($i == date("Y"))
                                                                        $output .="selected ";
                                                        $output .= ">".$i."</option>";
                                                         }

                                                	$ouptput .="</select>";
                                                }
                                                
                                                if($type == "hidden"){
                                                        //query here is the caption, leave it empty if you don't to show anything, still the stuff will look bad
                                                        $output .= $query;
                                                        $output .= "<input type='hidden' name='".$id."' value='".$v."'>";
                                                }
                                         $output .= "</td></tr>";
                                        }
   	 			}
   	 		}
   	 	}else{
   	 		//if we have the content ready there.
   	 		$output .= $this->content;
   	 	}
   	 		
   	 	//action, needed to set up what we need to do for update form
   	 	$output .= "<input type=hidden name=table value='".$this->table."'>";
   	 	
   	 	//add indexname and id if possible
   	 	if($this->index && $this->indexname){
   	 	$output .= "<input type=hidden name=index value='".$this->index."'>";
   	 	$output .= "<input type=hidden name=indexname value='".$this->indexname."'>";
   	 	}
   	 	
   	 	//other hidden publiciables you want to add 
   	 	// it will add -o to them to differentiate it from normal ones
   	 	if(is_array($this->variables)){
   	 		while (list($n,$v) = each($this->variables))
   	 			$output .= "<input type=hidden name='".$n."-o' value='".$v."'>";
   	 	}
   	 	
   	 	
   	 	//add the  button with desired value 
   	 	$output .= "<tr><td></td><td><input type=submit name=submit value='".$this->submit."'></td></tr>";
   	 	
   	 	

   	 	
   	 	$output .= "</form></table>";
   	 	return $output;
   	 }else{
   	 	return false;
   	 }
   }
   
   /**
    * updates the form
    *
    */
   function UpdateForm(){
   	   	global $config;
               // print_r($_REQUEST);
                //exit();
   	   	//starting to handle according to properties
		
   	   	if(is_array($this->handle)){
   	   		while (list ($key,$value) = each ($this->handle))
   	   			$process[$key]= $value;
   	   	}else{ 	
   	   		while (list ($key,$value) = each ($_REQUEST))
   	   			$process[$key]= $value;
   	   	}
   	   	
   	   //start the probing
           
   	   	if(is_array($process)){
   	   		//determine operation
		if(!$this->operation){
   	   		if(strpos(strtoupper($process['submit']),"ELETE") != false){
   	   			$operation = "delete";
			}elseif (strpos(strtoupper($process['submit']),"DD") != false || strpos(strtoupper($process['submit']),"STER") != false){
   	   			$operation = "add";
			}elseif (strpos(strtoupper($process['submit']),"DIT") != false || strpos(strtoupper($process['submit']),"PDATE") != false){
   	   			$operation = "edit";
			}else{
   	   			echo "Can't determine operation";
   	   			return false;
   	   		}
		
		}else{
			$operation = $this->operation;
		}
			
                        
   	   		//operation figured out, delete is the easiest
   	   		if($operation == "delete")
                                //you're sure, lets delete then
                                dbQuery("DELETE FROM ".$process['t']." WHERE ".$process['indexname']."='".$process['index']."'") or die(dbError());
   	   			
   	   			 
   	   		//Add, that means insert for your mysql frined
   	   		//prep the values
   	   		if($operation == "add" || $operation == "edit"){
   	   			while (list($key,$value) = each ($process)){
                                       
   	   				if(substr($key,-2,2) != "-o" && $key != "submit" && $key != "table" && $key != "index" && $key != "indexname" && strpos($key,"__") === false && strpos($key,"PHP") === false && strpos($key,"fc") === false && strpos($key,"km_") === false){ 
   	   					//get rid of those pesky javascript values
                                                $key = str_replace("_value=","",$key);
                                                
                                                if($operation == "add"){
   	   					//create keys string
   	   					if($keys == "")
   	   						$keys = $key;
   	   					else 
   	   						$keys .= ",".$key;
   	   					
   	   					//create values string
   	   					if($values == "")
   	   						$values = $value;
   	   					else 
   	   						$values .= "','".$value;
   	   					}else{
   	   					if ($string == "")
   	   						$string = $key."='".$value."'";
   	   					else 	
   	   						$string .= ",".$key."='".$value."'";
   	   					}
   	   				}
   	   			}
                                
 
                                
   	   			//insert or update, depending on what you sent
				//echo "INSERT INTO ".$process['table']." (".$keys.") VALUES ('".$values."')";
				if(!$this->table)
					$this->table = $process['table'];
					
   	   			if($operation == "add")
   	   				dbQuery("INSERT INTO ".$this->table." (".$keys.") VALUES ('".$values."')") or die(dbError());
   	   			else 
   	   				dbQuery("UPDATE ".$process['table']." SET ".$string." WHERE ".$process['indexname']."='".$process['index']."'") or die(dbError());	
   	   				//"UPDATE ".$process['table']." SET ".$string." WHERE ".$process['indexname']."='".$process['index']."'";
   	   				//print_r($_REQUEST);
                           	   		
                        
                        }
                               //Handle file uploads
                          
                                        while (list ($index, $file) = each ($_FILES)) {
                                                if($file[size] > 0){
                                                        //get the extenstion
                                                        $ext            = substr($file['name'],strpos($file['name'],"."),strlen($file['name']));
                                                        if($operation == "add")
                                                                $I      = dbInsertID();
                                                        else
                                                                $I      = $process['index'];      
                                                        
                                                        ///compose the file name
                                                        $filename       = $index."-".$I.$ext;
                                                        
                                                        //move the file
                                                        move_uploaded_file($file[tmp_name],$config['file_dir']."/".$filename) or die(print_r($file));
                                                        
                                                        //Update the DB
                                                        dbQuery("Update ".$process['table']." set ".$index." = '".$filename."' where ".$process['indexname']." = '".$I."'");
                                                        }
                                        }
                                        
                               
   	   			if($this->notify){
   	   			$parse  = "<script language='javascript'>";   	   			
   	   			$parse .= "alert('Update successful, Click ok to go back');";
   	   			$parse .=  "this.location = '".$this->BackURL."'</script>"; 
   	   			
   	   			echo $parse;
   	   			}else{
   	   				if($this->BackURL)
   	   					header("Location: ".$this->BackURL);
   	   				
   	   			}
   	   	}else{
   	   			echo "<script language='javascript'>alert('Update Failed, Click ok to go back');history.back(1)</script>";
   	   	}
   	    
   }
/**
 * strips -o from all the (non database publiciables sent)
 *
 * @return array resembles $_REQUEST
 */
function GetRequest(){
		while(list($key,$value) = each($_REQUEST)){
			if(substr($key,-2,2) == "-o")
				$key = substr($key,0,strlen($key)-2);
				$output[$key]	= $value;
		}
		return $output;
}

	/**
	 * Replaces keys placed between ## from the row in the db with actual values according to the query
	 *
	 * @param dbrow $row
	 * @param the string $string
	 * @return link, a string
	 */
	function ReplaceKeys($row,$string){
		reset($row);
		while(list($key,$value) = each($row)){
			$keys[] = "##".$key."##";
			$values[] = $value;	
		}
		$link = str_replace($keys,$values,$string);
	return $link;
	}
}
?>